package com.rockcent.mall.helper;


import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.MerchantGiftPacketCouponDto;
import com.rockcent.mall.lib.dto.MerchantGiftPacketProductDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.repository.*;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by DK on 16/10/11.
 */
@Component
public class GiftPacketHelper {
    private final Logger log = LoggerFactory.getLogger(GiftPacketHelper.class);
    @Autowired
    private MerchantGiftPacketProductRepository merchantGiftPacketProductRepository;

    @Autowired
    private MerchantGiftPacketCouponRepository merchantGiftPacketCouponRepository;

    @Autowired
    private MerchantProductRepository merchantProductRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private MerchantCouponRepository merchantCouponRepository;

    @Autowired
    private ProductQuantityRepository productQuantityRepository;

    @Autowired
    private MarketMerchantProductSalesRepository marketMerchantProductSalesRepository;

    @Autowired
    private MarketMerchantCooperationRepository marketMerchantCooperationRepository;

    @Autowired
    private MerchantProductStatisticsRepository merchantProductStatisticsRepository;


    //校验礼包赠送卡卷数量
    public Map<Long, String> checkCoupon(List<MerchantGiftPacketCouponDto> merchantGiftPacketCouponDtoList){
        HashedMap map = new HashedMap();
        if (merchantGiftPacketCouponDtoList != null && merchantGiftPacketCouponDtoList.size() > 0) {
            for (MerchantGiftPacketCouponDto couponStr : merchantGiftPacketCouponDtoList) {
                MerchantCoupon coupon = merchantCouponRepository.findOne(couponStr.getCouponId());
                if (couponStr.getUseNumber() > coupon.getLeaveTotal()) {
                    map.put(coupon.getId(), coupon.getName());
                }
            }
        }
        return map;
    }

    //校验礼包包含的产品
    public Map<String, Map<Long, String>> checkProduct(Product masterProduct,  MerchantGiftPacketProductDto giftPacketProductDto, List<MerchantGiftPacketProductDto> giftPacketProductDtoList) {
        Map<String, Map<Long, String>> resultMap = new HashMap<>();

        Map<Long, String> mapQuantity = new HashedMap();
        Map<Long, String> mapFee = new HashedMap();
        Map<Long, String> mapAudit = new HashedMap();
        Map<Long, String> mapResellFee = new HashedMap();
        Map<Long, String> mapStatus = new HashedMap();
        BigDecimal resellFee =  BigDecimal.valueOf(0);
        if (Double.valueOf(masterProduct.getResellFee().toString()) == 0D) {
            mapFee.put(masterProduct.getId(), masterProduct.getName());
        }
        if (masterProduct.getMarketId() != null) {
            Merchant merchant = merchantRepository.findOne(masterProduct.getMarketMerchantId());
            if (merchant.getProdAudit()) {
                mapAudit.put(masterProduct.getId(), masterProduct.getName());
            }
        }
        if (ProductStatus.SELLING != masterProduct.getStatus()) {
            mapStatus.put(masterProduct.getId(), masterProduct.getName());
        }

        if (giftPacketProductDto.getResellFee() != null) {
            resellFee = resellFee.add(giftPacketProductDto.getResellFee());
        }

        ProductQuantity ProductQuantity = productQuantityRepository.findOne(masterProduct.getProductQuantityId());

        if (ProductQuantity.getQuantity() < giftPacketProductDto.getUseNumber()) {
            mapQuantity.put(masterProduct.getId(), masterProduct.getName());
        }

        if (giftPacketProductDtoList != null && giftPacketProductDtoList.size() > 0) {
            for (MerchantGiftPacketProductDto dto : giftPacketProductDtoList) {
                Product product = merchantProductRepository.findByIdAndMerchantId(dto.getProductId(), dto.getMerchantId());
                ProductQuantity quantity = productQuantityRepository.findOne(masterProduct.getProductQuantityId());
                if (Double.valueOf(product.getResellFee().toString()) == 0D ) {
                    mapFee.put(product.getId(), product.getName());
                }
                if (product.getMarketId() != null) {
                    Merchant merchant = merchantRepository.findOne(product.getMarketMerchantId());
                    Product marketProduct = merchantProductRepository.findOne(product.getMarketId());
                    if (merchant.getProdAudit()) {
                        mapAudit.put(marketProduct.getId(), marketProduct.getName());
                    }
                    if (quantity.getQuantity() < dto.getUseNumber()) {
                        mapQuantity.put(marketProduct.getId(), marketProduct.getName());
                    }
                }
                if (quantity.getQuantity() < dto.getUseNumber()){
                    mapQuantity.put(product.getId(), product.getName());
                }
                if (ProductStatus.SELLING != product.getStatus()) {
                    mapStatus.put(masterProduct.getId(), masterProduct.getName());
                }
                if (dto.getResellFee() != null) {
                    resellFee = resellFee.add(dto.getResellFee());
                }
            }
        }

        mapResellFee.put(0L, resellFee.toString());
        resultMap.put("audit", mapAudit);
        resultMap.put("fee", mapFee);
        resultMap.put("quantity", mapQuantity);
        resultMap.put("mapStatus", mapStatus);
        resultMap.put("resellFee", mapResellFee);
        return resultMap;
    }

    /**
     * 礼包产品
     * @param giftPacketId 礼包ID
     * @param packetProduct
     * @param type 礼包产品类型 MASTER(主产品) COLLOCATION(搭配产品)
     */
    public void saveMerchantGiftPacketProduct(Long giftPacketId, MerchantGiftPacketProductDto packetProduct, GiftPacketProductType type){
        MerchantGiftPacketProduct giftPacketProducts = new MerchantGiftPacketProduct();
        giftPacketProducts.setPacketId(giftPacketId);
        giftPacketProducts.setProductId(packetProduct.getProductId());
        giftPacketProducts.setPacketPrice(packetProduct.getPacketPrice());
        giftPacketProducts.setUseNumber(packetProduct.getUseNumber());
        giftPacketProducts.setGiftPacketProductType(type);
        giftPacketProducts.setProductId(packetProduct.getProductId());
        giftPacketProducts.setMerchantId(packetProduct.getMerchantId());
        giftPacketProducts.setMarketId(packetProduct.getProductId());
        giftPacketProducts.setMarketMerchantId(packetProduct.getMerchantId());
        if (packetProduct.getMarketId() != null) {
            giftPacketProducts.setMarketId(packetProduct.getMarketId());
            giftPacketProducts.setMarketMerchantId(packetProduct.getMarketMerchantId());
        }
        merchantGiftPacketProductRepository.save(giftPacketProducts);
    }

    /**
     * 礼包卡卷
     * @param giftPacketId 礼包ID
     * @param packetCoupon
     */
    public void saveMerchantGiftPacketCoupon(Long giftPacketId, MerchantGiftPacketCouponDto packetCoupon){
        MerchantGiftPacketCoupon giftPacketCoupons = new MerchantGiftPacketCoupon();
        giftPacketCoupons.setPacketId(giftPacketId);
        giftPacketCoupons.setCouponId(packetCoupon.getCouponId());
        giftPacketCoupons.setUseNumber(packetCoupon.getUseNumber());
        giftPacketCoupons.setMerchantId(packetCoupon.getMerchantId());
        merchantGiftPacketCouponRepository.save(giftPacketCoupons);

        //针对相对应卡卷数量进行减少,冻结使用数量
        MerchantCoupon merchantCoupon = merchantCouponRepository.findOne(packetCoupon.getCouponId());
        merchantCoupon.setLeaveTotal(merchantCoupon.getLeaveTotal() - packetCoupon.getUseNumber());
        merchantCoupon.setQuantityFrozen(merchantCoupon.getQuantityFrozen() + packetCoupon.getUseNumber());
        merchantCouponRepository.save(merchantCoupon);
    }

    public void saveMarketMerchantCooperation(UserInfoDto userInfoDto, Long merchantId){
        Merchant merchant = merchantRepository.findOne(merchantId);
        MarketMerchantCooperation marketMerchantCooperation = new MarketMerchantCooperation();
        marketMerchantCooperation.setSupplierMerchantId(merchant.getId());
        marketMerchantCooperation.setSupplierMallId(merchant.getMallId());
        marketMerchantCooperation.setDistributorMerchantId(userInfoDto.merchant.getId());
        marketMerchantCooperation.setDistributorMallId(userInfoDto.mall.getId());
        marketMerchantCooperation.setStatus(MarketMerchantCooperationStatus.PASS);
        marketMerchantCooperationRepository.save(marketMerchantCooperation);
    };

    public  Product isSelfProduct(UserInfoDto userInfoDto, MerchantGiftPacketProductDto masterPacketProduct) {
        Product marketProduct = merchantProductRepository.findByIdAndMerchantIdAndMallId(masterPacketProduct.getProductId(), userInfoDto.merchant.getId(), userInfoDto.mall.getId());
        if (marketProduct == null && masterPacketProduct.getMarketId() != null) {
            marketProduct = merchantProductRepository.findByIdAndMerchantIdAndMallId(masterPacketProduct.getMarketId(), userInfoDto.merchant.getId(), userInfoDto.mall.getId());
        }
        Product mProduct = merchantProductRepository.findByMarketIdAndMerchantIdAndMallIdAndIsDeleteAndStatus(masterPacketProduct.getProductId(), userInfoDto.merchant.getId(), userInfoDto.mall.getId(), Whether.NO, ProductStatus.SELLING);
        if (marketProduct == null && mProduct != null) {
            marketProduct = mProduct;
        }
        if (marketProduct == null) {
            marketProduct = new Product();
            // 分销关系表 插入一条记录
            MarketMerchantProductSales productSales = new MarketMerchantProductSales();

            Product product = merchantProductRepository.findOne(masterPacketProduct.getProductId());
            RBeanUtils.copyProperties(product, marketProduct, "id", "dateCreated", "lastUpdated", "cAccessUrl", "promoteUrl");
            marketProduct.setMarketId(product.getId());//当marketId 存在时,证明产品是分销的
            marketProduct.setShareFee(BigDecimal.ZERO);
            marketProduct.setMerchantId(userInfoDto.merchant.id);
            marketProduct.setMallId(userInfoDto.mall.getId());
            marketProduct.setMarketMallId(product.getMallId());
            marketProduct.setMarketMerchantId(product.getMerchantId());
            marketProduct.setMarketMerchantName(product.getMerchantName());
            marketProduct.setMerchantName(userInfoDto.merchant.getName());
            marketProduct.setMarketPlatformType(ProductMarketPlatformType.IN_PLATFORM);

            productSales.setProductId(product.getId());
            productSales.setSupplierMallId(product.getMallId());
            productSales.setSupplierMerchantId(product.getMerchantId());
            if (product.getMarketId() != null) {
                marketProduct.setMarketId(product.getMarketId());
                marketProduct.setMarketMallId(product.getMarketMallId());
                marketProduct.setMarketMerchantId(product.getMarketMerchantId());
                marketProduct.setMarketMerchantName(product.getMarketMerchantName());
                productSales.setProductId(product.getMarketId());
                productSales.setSupplierMallId(product.getMarketMallId());
                productSales.setSupplierMerchantId(product.getMarketMerchantId());

            }

            if (product.getMallId() != userInfoDto.mall.getId()) {
                marketProduct.setMarketPlatformType(ProductMarketPlatformType.OUT_PLATFORM);
            }
            marketProduct = merchantProductRepository.save(marketProduct);

            //产品统计表
            ProductStatistics productStatistics = new ProductStatistics();
            productStatistics.setMallId(marketProduct.getMallId());
            productStatistics.setMerchantId(marketProduct.getMerchantId());
            productStatistics.setProductId(marketProduct.getId());
            productStatistics.setMarketProductId(product.getId());
            merchantProductStatisticsRepository.save(productStatistics);

            productSales.setDistributorMallId(userInfoDto.merchant.getMallId());
            productSales.setDistributorMerchantId(userInfoDto.merchant.getId());
            productSales.setDistributorStatus(MarketMerchantProductSalesStatus.PASS);
            productSales.setSupplierStatus(MarketMerchantProductSalesStatus.PASS);
            marketMerchantProductSalesRepository.save(productSales);
        }
        return marketProduct;
    }
}
